<template>
  <div class="h-screen overflow-hidden bg-[#F7F8FA] flex">
    <Nav></Nav>
    <div class="flex-1 bg-[#FFFFFF] overflow-hidden">
      <el-container class="h-full">
        <div class="flex h-full p-0 w-[100%] overflow-hidden">
          <!-- 左侧树形面板 -->
          <div ref="splitRef"
            class="w-64 border-r border-solid border-[var(--el-border-color-lighter)] overflow-hidden">
            <ele-split-panel ref="splitRef" flex-table size="256px" allow-collapse
              :custom-style="{ borderWidth: '0 1px 0 0' }" class="h-full">
              <!-- 科目和地区选择 -->
              <div class="p-4 border-b border-[var(--el-border-color-lighter)]">
                <!-- <div class="flex items-center mb-4">
                  <el-select v-model="subject" placeholder="数学" class="w-[130px] mr-2">
                    <el-option label="数学" value="math" />
                    <el-option label="语文" value="chinese" />
                    <el-option label="英语" value="english" />
                  </el-select>

                  <el-button type="primary" :icon="LocationFilled"
                    class="w-[100px] mr-2 overflow-hidden text-ellipsis whitespace-nowrap"
                    @click="showAreaSelector = true">
                    {{ selectedArea?.name || '地区' }}
                  </el-button>
                </div> -->

                <!-- 年级选择 -->
                <div class="flex justify-between items-center">
                  <div class="text-[var(--el-color-primary)] text-sm">{{ selectedGradeText }}</div>
                  <el-button @click="showGradeSelector = true" size="small">选择</el-button>
                </div>
              </div>

              <!-- 选择器组件 -->
              <area-selector v-model="showAreaSelector" :default-value="selectedArea" @confirm="handleAreaConfirm" />
              <grade-selector v-model="showGradeSelector" :default-value="selectedGrade"
                @confirm="handleGradeConfirm" />

              <!-- 树形结构 -->
              <div v-loading="loading" class="flex-1 flex flex-col" style="height: calc(100% - 120px);">
                <el-tree 
                  ref="treeRef" 
                  :data="data" 
                  highlight-current 
                  node-key="id" 
                  :props="{ label: 'name' }"
                  :expand-on-click-node="false" 
                  :default-expanded-keys="defaultExpandedKeys"
                  :filter-node-method="filterNode"
                  class="[--ele-tree-item-height:34px] px-4 py-2 overflow-y-auto h-full" 
                  @node-click="handleNodeClick"
                >
                <template #default="scope">
                    <el-icon class="mr-1.5 text-base">
                      <FolderOutlined v-if="scope.data.children?.length" style="color: rgb(255,214,89); fill: rgb(255,214,89)" />
                      <FileOutlined v-else class="scale-90 translate-y-[1px] text-[#faad14]" />
                    </el-icon>
                    <span class="mt-0.5">{{ scope.data.name }}</span>
                  </template>
                </el-tree>
              </div>
            </ele-split-panel>
          </div>

          <!-- 右侧内容区域 -->
          <div class="flex-1 p-4 overflow-auto">
            <filterSection @change="handleFilterChange" class="mb-4" />
            <Topic :current="current" :filters="filters" />
          </div>
        </div>
      </el-container>
    </div>
  </div>
</template>
<script setup>
import Nav from "@/components/nav/index.vue";

// 在 import 部分添加 ele-loading 组件的导入
import { ref, nextTick, watch, reactive, markRaw, computed } from 'vue';
import { ElMessage as EleMessage, ElLoading } from 'element-plus';
import { toTree } from '@/utils/tree';
import {
  FolderOutlined,
  FileOutlined
} from '@/components/icons/index.js';
import { useMobile } from '@/utils/use-mobile';
import AreaSelector from '@/components/area-selector/index.vue';
import { LocationFilled } from '@element-plus/icons-vue';
import GradeSelector from '@/components/grade-selector/index.vue';
import filterSection from '@/components/question/filter-section.vue';
import Topic from '@/components/question/topic.vue';
import { onMounted } from 'vue';
import {
  getChapterList,
  getQuestionList
} from '@/api/question'

const subject = ref('math');
/** 是否是移动端 */
const { mobile } = useMobile();

/** 分割面板组件 */
const splitRef = ref(null);

/** 树组件 */
const treeRef = ref(null);

/** 加载状态 */
const loading = ref(true);

/** 树形数据 */
const data = ref([]);

/** 选中数据 */
const current = ref(null);

/** 机构搜索关键字 */
const keywords = ref('');

/** 是否显示表单弹窗 */
const showEdit = ref(false);

/** 编辑回显数据 */
const editData = ref(null);

/** 添加时上级 */
const organizationId = ref();

const showAreaSelector = ref(false);
const showGradeSelector = ref(false);
const selectedGrade = ref(null);

const selectedGradeText = computed(() => {
  if (!selectedGrade.value) return '请选择版本和年级';
  return `${selectedGrade.value.version.label}：${selectedGrade.value.grade.label}`;
});

const handleGradeConfirm = (grade) => {
  selectedGrade.value = grade;
};
const selectedArea = ref(null);

const handleAreaConfirm = (area) => {
  selectedArea.value = area;
};

/** 查询 */
const query = () => {
  loading.value = true;
  getChapterList({
    subject: subject.value,
    area: selectedArea.value?.id,
    grade: selectedGrade.value?.grade.value
  })
    .then((res) => {
      loading.value = false;
      data.value = toTree({
        data: res,
        idField: 'id',
        parentIdField: 'parentId'
      });
      nextTick(() => {
        handleNodeClick(data.value[0]);
      });
    })
    .catch((e) => {
      loading.value = false;
      EleMessage.error(e.message);
    });
};

/** 选择数据 */
const handleNodeClick = (row) => {
  if (mobile.value && current.value) {
    splitRef.value?.toggleCollapse?.(true);
  }

  if (row?.id) {
    current.value = row;
    treeRef.value?.setCurrentKey?.(row.id);
  } else {
    current.value = null;
  }
};

/** 打开编辑弹窗 */
const openEdit = (item, id) => {
  editData.value = item ?? null;
  organizationId.value = id;
  showEdit.value = true;
};



/** 树过滤方法 */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name?.includes(value);
};

/** 树过滤 */
watch(keywords, (value) => {
  treeRef.value?.filter?.(value);
});

const defaultExpandedKeys = computed(() => {
  const firstLevel = data.value.filter(item => item.parentId === '0');
  const secondLevel = data.value.filter(item => 
    firstLevel.some(first => first.id === item.parentId)
  );
  
  return [...firstLevel, ...secondLevel].map(item => item.id);
});
// api调用
// query();

// 静态调用
loading.value = false;
data.value = toTree({
  data: [
    {
      id: '1',
      name: '一 5以内数的认识和加、减法',
      parentId: '0'
    },
    {
      id: '1-1',
      name: '1.1~5的认识',
      parentId: '1'
    },
    {
      id: '1-1-1',
      name: '1-5的认识',
      parentId: '1-1'
    },
    {
      id: '1-1-2',
      name: '比大小',
      parentId: '1-1'
    },
    {
      id: '1-1-3',
      name: '第几',
      parentId: '1-1'
    },
    {
      id: '1-1-4',
      name: '分与合',
      parentId: '1-1'
    },
    {
      id: '1-2',
      name: '2.1～5的加、减法',
      parentId: '1'
    },
    {
      id: '1-2-1',
      name: '加法',
      parentId: '1-2'
    },
    {
      id: '1-2-2',
      name: '减法',
      parentId: '1-2'
    },
    {
      id: '1-3',
      name: '3.0的认识和加、减法',
      parentId: '1'
    },
    {
      id: '2',
      name: '二 6~10的认识和加、减法',
      parentId: '0'
    },
    {
      id: '2-1',
      name: '1.6~9的认识',
      parentId: '2'
    },
    {
      id: '2-1-1',
      name: '6~9的认识',
      parentId: '2-1'
    },
    {
      id: '2-1-2',
      name: '分与合',
      parentId: '2-1'
    },
    {
      id: '2-2',
      name: '2.6~9的加、减法',
      parentId: '2'
    },
    {
      id: '2-2-1',
      name: '6和7的加、减法',
      parentId: '2-2'
    },
    {
      id: '2-2-2',
      name: '8和9的加、减法',
      parentId: '2-2'
    },
    {
      id: '2-3',
      name: '3.10的认识和加、减法',
      parentId: '2'
    },
    {
      id: '2-3-1',
      name: '10的认识',
      parentId: '2-3'
    },
    {
      id: '2-3-2',
      name: '10的加、减法',
      parentId: '2-3'
    },
    {
      id: '2-3-3',
      name: '连加、连减',
      parentId: '2-3'
    },
    {
      id: '2-3-4',
      name: '加、减混合',
      parentId: '2-3'
    },
    {
      id: '3',
      name: '三 认识立体图形',
      parentId: '0'
    },
    {
      id: '4',
      name: '四 11~20的认识',
      parentId: '0'
    },
    {
      id: '4-1',
      name: '10的再认识',
      parentId: '4'
    },
    {
      id: '4-2',
      name: '11~20的认识',
      parentId: '4'
    },
    {
      id: '4-3',
      name: '简单加、减法',
      parentId: '4'
    },
    {
      id: '5',
      name: '五 20以内的进位加法',
      parentId: '0'
    },
    {
      id: '5-1',
      name: '9加几',
      parentId: '5'
    },
    {
      id: '5-2',
      name: '8、7、6加几',
      parentId: '5'
    },
    {
      id: '5-3',
      name: '5、4、3、2加几',
      parentId: '5'
    }
  ],
  idField: 'id',
  parentIdField: 'parentId'
});

// 添加筛选条件状态
const filters = ref({})

// 修正筛选条件处理函数
const handleFilterChange = (newFilters) => {
  filters.value = newFilters
}


onMounted(() => {
  // 延迟执行以确保DOM已经渲染
  setTimeout(() => {
    if (splitRef.value) {
      // 尝试触发分割面板的更新
      splitRef.value.update?.();
    }
  }, 100);
});
</script>

<style scoped>
/* 由于 ele-split-panel-body 的样式涉及到组件内部样式覆盖，
   这部分暂时保留使用原始 CSS，因为可能需要特定的选择器权重 */
.ele-split-panel-body {
  overflow: auto !important;
  height: 100% !important;
  padding: 0 !important;
}

:deep(.ele-split-panel-body) {
  display: block !important;
  visibility: visible !important;
}
</style>
